package com.hemaapp.yjnh.activity;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.image.load.XtomImageTask;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.view.UUHorizonalScrollView;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.FarmerListAdapter;
import com.hemaapp.yjnh.bean.Client;
import com.hemaapp.yjnh.bean.HotDistrict;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.LoginUtil;

/**首页-田家
 * @author GuiyouZhang
 * Date：2015年12月14日 下午2:09:36
 * Email:guiyouzhang@163.com
 */
public class FarmerActivity extends BaseActivity implements OnClickListener{

	private TextView titleText;
	private ImageButton titleLeft;
	private Button titleRight;
	private ImageView titleRightImg;

	private RefreshLoadmoreLayout refreshLayout;
	private View headerView;
	private XtomListView listview;//推荐田家

	private TextView tvSearch;
	private TextView tvHotArea;
	private UUHorizonalScrollView hotAreaScrollView;
	private LinearLayout ll_recommend_goods;//推荐商品布局
	private TextView tv_location;//定位城市
    private TextView tvRecomCustom;
    private TextView tvRecomGoods;

	private ArrayList<HotDistrict> hotDistricts = new ArrayList<HotDistrict>();//热门区域
	private ArrayList<Client> recommendClients = new ArrayList<Client>();//推荐田家
	private FarmerListAdapter adpter;
	private String city = "济南";//当前所在区域
	private User user;
	private int districtPage = 0;
	private int farmPage = 0;
    private int groupWide = 0;//推荐商品每一组数据的宽度
    private int groupNum = 3;//根据手机屏幕不同需要显示的推荐商品组的数量也不一样，最少3个
    private int screenWide = 0;//当前屏幕的宽度
    private LoginUtil.LoginCallBack loginCallBack;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_farmer);
		user = getApplicationContext().getUser();
		super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
		screenWide = XtomWindowSize.getWidth(mContext);
		init();
	}
	
	private void init() {
		headerView = LayoutInflater.from(mContext).inflate(R.layout.header_activity_farmer_, null);
		findHeaderViews();
		listview.addHeaderView(headerView);
		getNetWorker().hotDistrictList("3", "", districtPage+"");//获取热门城市信息
		getFarmerList();//附近的田家
	}

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**获取附近的田家
	 * 
	 */
	private void getFarmerList() {
		String token = user == null?"":user.getToken();
		getNetWorker().clientList(token, "2", city, "1", "0", "", farmPage+"", "", "");
	}

	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
			case CLIENT_LIST:
            case HOTDISTRICT_LIST:
				showProgressDialog("请稍候");
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
			case CLIENT_LIST:
            case HOTDISTRICT_LIST:
				cancelProgressDialog();
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask, HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case HOTDISTRICT_LIST:
			HemaPageArrayResult<HotDistrict> dResult = (HemaPageArrayResult<HotDistrict>) baseResult;
			if (dResult == null || dResult.getObjects() == null)
				return;
			hotDistricts.clear();
			hotDistricts.addAll(dResult.getObjects());
			setGoods();
			break;
		case CLIENT_LIST:
			String page = netTask.getParams().get("page");
			HemaPageArrayResult<Client> cResult = (HemaPageArrayResult<Client>) baseResult;
			if (cResult == null || cResult.getObjects() == null)
				return;
			ArrayList<Client> clients = cResult.getObjects();
			if ("0".equals(page)) {// 刷新
				refreshLayout.refreshSuccess();
				recommendClients.clear();
				this.recommendClients.addAll(clients);
			}else {
				refreshLayout.loadmoreSuccess();
				if (clients.size() > 0)
					this.recommendClients.addAll(clients);
				else {
					refreshLayout.setLoadmoreable(false);
					XtomToastUtil.showShortToast(mContext, "已经到最后啦");
				}
			}
			refreshClient(-1);
			break;
		case CLIENT_LOGIN:
            HemaArrayResult<User> uResult = (HemaArrayResult<User>) baseResult;
            user = uResult.getObjects().get(0);
            getApplicationContext().setUser(user);
			break;
		default:
			break;
		}

	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case HOTDISTRICT_LIST:
            showTextDialog(baseResult.getMsg());
			break;
		case CLIENT_LIST:
			String page = netTask.getParams().get("page");
			if ("0".equals(page)) {// 刷新
				refreshLayout.refreshFailed();
			}else {
				refreshLayout.loadmoreFailed();
			}
            XtomToastUtil.showShortToast(mContext, "获取田家失败，"+baseResult.getMsg());
            showTextDialog(baseResult.getMsg());
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case HOTDISTRICT_LIST:
			showTextDialog("获取信息失败");
			break;
		case CLIENT_LIST:
			String page = netTask.getParams().get("page");
			if ("0".equals(page)) {// 刷新
				refreshLayout.refreshFailed();
			}else {
				refreshLayout.loadmoreFailed();
			}
            XtomToastUtil.showShortToast(mContext, "获取田家失败，请稍后再试");
			refreshClient(failedType);
			break;
		default:
			break;
		}
	}
	
	/**刷新田家列表
	 * 
	 */
	private void refreshClient(int failedType) {
        if (null == adpter) {
            adpter = new FarmerListAdapter(mContext, recommendClients);
            adpter.setEmptyString("暂无田家");
            listview.setAdapter(adpter);
        }else {
            adpter.notifyDataSetChanged();
        }
        adpter.setFailtype(failedType);
	}
	
	/**热门区域
	 * 
	 */
	private void setGoods() {
		// 动态添加多个商品
		if (ll_recommend_goods.getChildCount() != 0) {
			ll_recommend_goods.removeAllViews();
		}
		for (int j = 0; j < groupNum; j++) {
			for (int i = 0; i < hotDistricts.size(); i++) {
				HotDistrict district = hotDistricts.get(i);
				View view = LayoutInflater.from(mContext).inflate(
						R.layout.layout_hot_district, null);
				ItemViewHolder ivHolder = new ItemViewHolder();
				itemFindView(view, ivHolder);
				setItem(district, view, ivHolder);
				if (j == 0) {
					view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
	                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
					groupWide += view.getMeasuredWidth();
				}
				view.setTag(district);
				view.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						try {
							HotDistrict district1 = (HotDistrict) v.getTag();
							//记录点击
							String token = "";
							if (user != null) {
								token = user.getToken();
							}
							getNetWorker().ADRecord(token, "4", district1.getId());
							
							String[] areas = district1.getdistrict_name()
									.split("—");
							Intent itLocation = new Intent(mContext, FarmerListActivity.class);
							itLocation.putExtra("keyid", areas[areas.length - 1]);
							itLocation.putExtra("title", areas[areas.length - 1]);
							itLocation.putExtra("change", false);
							startActivity(itLocation);
						} catch (Exception e) {
							showTextDialog("地区数据异常\n请稍后再试");
						}
					}
				});
			}
			if (j == 0 && groupWide > 0) {
				if (groupWide <screenWide) {
					groupNum = 1;
				}else {
					groupNum += (screenWide / groupWide);
				}
			}
		}
		hotAreaScrollView.setGroupWide(groupWide);
	}

	@Override
	protected void findView() {
		titleText = (TextView) findViewById(R.id.title_text);
		titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
		titleRight = (Button) findViewById(R.id.title_right_btn);
		titleRightImg = (ImageView) findViewById(R.id.title_right_img);

		refreshLayout = (RefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
		listview = (XtomListView) findViewById(R.id.listview);
	}
	
	private void findHeaderViews() {
		tvSearch = (TextView) headerView.findViewById(R.id.tv_search);
		tvHotArea = (TextView) headerView.findViewById(R.id.tv_hot_area);
		hotAreaScrollView = (UUHorizonalScrollView) headerView.findViewById(R.id.horizonal_limitless_scrollview);
		ll_recommend_goods = (LinearLayout) headerView.findViewById(R.id.layout_recommend_goods);
		tv_location = (TextView) headerView.findViewById(R.id.tv_location);
        tvRecomCustom = (TextView) headerView.findViewById(R.id.tv_recommended_custom);
        tvRecomGoods = (TextView) headerView.findViewById(R.id.tv_recommended_goods);

		//2016.10.31 start 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
//		city = XtomSharedPreferencesUtil.get(mContext, "city");
		city = XtomSharedPreferencesUtil.get(mContext, "city_farmer");
		if (isNull(city)) {
			city = XtomSharedPreferencesUtil.get(mContext, "city");
		}
		//2016.10.31 end 为了和iOS一致，这里田家、乐乐、走走、农需的地区都单独保存
		if (isNull(city)) {
			city = "定位失败";
		}
		tv_location.setText(city);
		tv_location.setOnClickListener(this);
		tvHotArea.setOnClickListener(this);
		tvSearch.setOnClickListener(this);
        tvRecomCustom.setOnClickListener(this);
        tvRecomGoods.setOnClickListener(this);
	}

	@Override
	protected void setListener() {
		titleText.setText("田家");
		titleLeft.setOnClickListener(this);
		titleRight.setVisibility(View.GONE);
		titleRightImg.setVisibility(View.VISIBLE);
		titleRightImg.setImageResource(R.drawable.head_farmer_1);
		titleRightImg.setOnClickListener(this);
		if (user != null) {//如果没登录那么去登录
			String role = user.getRole();
			//角色	0普通用户 1田家用户
			if (role.equals("1")) {
				titleRight.setVisibility(View.GONE);
				titleRightImg.setVisibility(View.VISIBLE);
			}else {
				//如果角色是普通用户，那么先去联网获取最新的状态，以防本地user不是最新的
				getNetWorker().clientLogin();
			}
		}

		refreshLayout.setRefreshable(false);
		refreshLayout.setLoadmoreable(true);
		refreshLayout.setOnStartListener(new StartListener());
	}

	private class StartListener implements OnStartListener {

		@Override
		public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
			//获取热门城市信息
			getNetWorker().hotDistrictList("3", "", districtPage+"");
			farmPage = 0;
			getFarmerList();
		}

		@Override
		public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
			farmPage++;
			getFarmerList();
		}
	}
	
	private class ItemViewHolder {
		private ImageView backImage;
		private TextView tv_district;
	}
	
	private void itemFindView(View view, ItemViewHolder ivHolder) {
		ivHolder.backImage = (ImageView) view.findViewById(R.id.iv_goods);
		ivHolder.tv_district = (TextView) view.findViewById(R.id.tv_district);
	}
	
	private void setItem(HotDistrict district, View view, ItemViewHolder ivHolder) {
		try {
			imageWorker.loadImage(new XtomImageTask(ivHolder.backImage, new URL(
					district.getimgurl()), mContext));
		} catch (MalformedURLException e) {
			ivHolder.backImage.setImageResource(R.drawable.no_pic_big);
			e.printStackTrace();
		}
		ivHolder.tv_district.setText(district.getdistrict_name());
		ll_recommend_goods.addView(view);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_img:
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        Intent itFarmer = new Intent();
                        if (user.getRole().equals("1")) {//角色	0普通用户 1田家用户
                            itFarmer.setClass(mContext, MyFarmerActivity.class);
                        } else if (user.getAuthflag().equals("1")) {//审核中的普通用户
                            itFarmer.setClass(mContext, FarmerProgressActivity.class);
                        } else {//普通田家
                            itFarmer.setClass(mContext, ApplyFarmerActivity0.class);
                        }
                        startActivity(itFarmer);
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.tv_location:
                Intent itLocation = new Intent(mContext, FarmerListActivity.class);
                itLocation.putExtra("keyid", city);
				itLocation.putExtra("title", "周边田家");
				itLocation.putExtra("change", true);
                startActivity(itLocation);
                break;
            case R.id.tv_hot_area:
                Intent itHot = new Intent(mContext, MoreHotAreaActivity.class);
                startActivity(itHot);
                break;
            case R.id.tv_search:
                Intent itSearch = new Intent(mContext, SearchActivity.class);
                itSearch.putExtra("assort", "田家");
                startActivity(itSearch);
                break;
            case R.id.tv_recommended_custom:
				Intent itCustom = new Intent(mContext, CmnCustomizeListWithSortActivity.class);
                itCustom.putExtra("title", "推荐定制");
				startActivity(itCustom);
                break;
            case R.id.tv_recommended_goods:
                Intent it = new Intent(mContext, CmnProductionListWithSortActivity.class);
                it.putExtra("title", "推荐商品");
                it.putExtra("keytype", "3");
                it.putExtra("keyid", "0");
                it.putExtra("keyword", "");
                it.putExtra("saleflag", "1");
                it.putExtra("topflag", "1");
                it.putExtra("cheapflag", "");
                it.putExtra("score_percent", "");
                it.putExtra("seller_id", "");
                it.putExtra("district_name", city);
                mContext.startActivity(it);
                break;
        }
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }else if (msg.getType() == EventBusConfig.UPDATE_FARMER_ADDRESS) {
            city = XtomSharedPreferencesUtil.get(mContext, "city_farmer");
            tv_location.setText(city);
            getFarmerList();
        }
    }
}
